package org.project.choujiang.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import org.project.choujiang.mapper.ActivityRepository;
import org.project.choujiang.mapper.DrawingCardRecordRepository;
import org.project.choujiang.mapper.GoodRepository;
import org.project.choujiang.mapper.UserRepository;
import org.project.choujiang.pojo.domain.Activity;
import org.project.choujiang.pojo.domain.DrawingCardRecord;
import org.project.choujiang.pojo.domain.Good;
import org.project.choujiang.pojo.domain.User;
import org.project.choujiang.pojo.dto.DrawingCardRecordDto;
import org.project.choujiang.pojo.ro.CalcDrawingRo;
import org.project.choujiang.pojo.ro.R;
import org.project.choujiang.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@RequestMapping(value ="activity")
@RestController
public class ActivityController {
    @Autowired
    private ActivityRepository activityRepository;

    @Autowired
    private DrawingCardRecordRepository drawingCardRecordRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private GoodRepository goodRepository;

    /**
     * 查询活动列表
     * @return
     */
    @GetMapping("findActivityList")
    public R<List<Activity>> findActivityList(){
        Sort sort = Sort.by(Sort.Direction.DESC, "createDate");
        return R.success(activityRepository.findAll(sort));
    }

    @GetMapping("findActivity/{id}")
    public R<Activity> findActivityList(@PathVariable String id){
        return R.success(activityRepository.findById(id).get());
    }

    /**
     * 添加编辑
     * @param activity
     * @return
     */
    @PostMapping("edit")
    public R<String> editActivity(@RequestBody Activity activity){
        AtomicReference<Integer> orderNum = new AtomicReference<>(1);
        activity.setCreateDate(new Date());
        activity.getPresentList().stream()
                        .forEach(ele->{
                            ele.setName("奖品"+(orderNum.getAndSet(orderNum.get() + 1)));
                        });
        activityRepository.save(activity);
        return R.success("");
    }

    /**
     * 活动删除
     * @param id
     * @return
     */
    @PostMapping("delete/{id}")
    public R<String> deleteActivity(@PathVariable String id){
        activityRepository.deleteById(id);
        drawingCardRecordRepository.deleteAllByActivityId(id);
        return R.success("");
    }


    /**
     * 某个活动的记录列表
     * @param id
     * @return
     */
    @PostMapping("recordList/{id}")
    public R<List<DrawingCardRecord>> recordList(@PathVariable String id){
        return R.success(drawingCardRecordRepository.findAllByActivityIdOrderByCreateDateDesc(id));
    }

    /**
     * 保存记录
     * @param drawingCardRecord
     * @return
     */
    @PostMapping("saveRecord")
    public R<String> saveRecord(@RequestBody DrawingCardRecord drawingCardRecord){
        drawingCardRecord.setCreateDate(new Date());
        drawingCardRecord.setUserId(TokenUtils.getLoginUserInfo().getId());
        drawingCardRecordRepository.save(drawingCardRecord);
        return R.success(null);
    }

    /**
     * 概率计算
     * @return
     */
    @PostMapping("calcDrawing")
    public R<String> calcDrawing(@RequestBody CalcDrawingRo calcDrawingRo){
        Activity activity = activityRepository.findById(calcDrawingRo.getActivityId()).get();
        List<DrawingCardRecord> allByActivityIdOrderByCreateDateDesc = drawingCardRecordRepository.findAllByActivityIdOrderByCreateDateDesc(calcDrawingRo.getActivityId());
        List<DrawingCardRecord> tmpList = new ArrayList<>();
        for (DrawingCardRecord drawingCardRecord : allByActivityIdOrderByCreateDateDesc) {
            if (Integer.valueOf(1).equals(drawingCardRecord.getPresentFlag())){
                break;
            }
            tmpList.add(drawingCardRecord);
        }

        int sum = tmpList.stream()
                .mapToInt(DrawingCardRecord::getDrawingNum)
                .sum();

        double persent = (calcDrawingRo.getDrawNum() + 0.0) / (activity.getOutNum() - sum);
        if (persent < 0 && persent > 1){
            return R.success("100");
        }else {
            return R.success(String.valueOf(Double.valueOf(persent*100).intValue()));
        }
    }

    /**
     * 查询抽卡记录
     * @return
     */
    @PostMapping("findDrawingCardList/{activityId}")
    public R<List<DrawingCardRecordDto>> findDrawingCardList(@PathVariable("activityId") String activityId){
        List<DrawingCardRecordDto> res = new ArrayList<>();
        Set<String> userIds = new HashSet<>();
        List<DrawingCardRecord> allByActivityIdOrderByCreateDateDesc = drawingCardRecordRepository.findAllByActivityIdOrderByCreateDateDesc(activityId);
        allByActivityIdOrderByCreateDateDesc.stream()
                .forEach(ele->{
                    DrawingCardRecordDto drawingCardRecordDto = new DrawingCardRecordDto();
                    res.add(drawingCardRecordDto);
                    userIds.add(ele.getUserId());
                    drawingCardRecordDto.setId(ele.getId());
                    drawingCardRecordDto.setDrawingNum(ele.getDrawingNum());
                    drawingCardRecordDto.setUserId(ele.getUserId());
                });


        Map<String, User> userMap = userRepository.findByIdIsIn(userIds)
                .stream()
                .collect(Collectors.toMap(ele -> ele.getId(), ele -> ele));

        for (DrawingCardRecordDto re : res) {
            User user = userMap.get(re.getUserId());
            if (ObjectUtil.isNotNull(user)){
                re.setNickname(user.getNickname());
            }
        }

        res.stream()
                .forEach(ele->{
                    List<Good> allByResourceIdAndUserId = goodRepository.findAllByResourceIdAndUserId(ele.getId(), ele.getUserId());
                    if (CollectionUtil.isNotEmpty(allByResourceIdAndUserId)){
                        ele.setGoodsFlag(1);
                    }else
                        ele.setGoodsFlag(0);
                });

        return R.success(res);
    }

    @PostMapping(value ="findRecord/{id}")
    public R<DrawingCardRecord> findRecord(@PathVariable("id") String id){
        return R.success(drawingCardRecordRepository.findById(id).get());
    }
}
